import userCenterBaseInfoApi from '@/api/userCenter/userCenterBaseInfoApi'
import userCenterUpdatePhoneApi from '@/api/userCenter/userCenterUpdatePhoneApi'
import CEmailOrPhoneCode from '@/components/user/CEmailOrPhoneCode'
import IUserCenterUpdatePhoneForm from '@/model/form/userCenter/IUserCenterUpdatePhoneForm'
import IUserBaseInfoVO from '@/model/vo/user/IUserBaseInfoVO'
import { useAppDispatch, useAppSelector } from '@/store'
import { setUserBaseInfo } from '@/store/user/userSlice'
import { onModalCancel, ToastError, ToastSuccess } from '@/util/CommonUtil'
import { passwordRSAEncrypt } from '@/util/UserUtil'
import Validator from '@/util/Validator'
import { Form, Modal } from '@douyinfe/semi-ui'
import { FormApi, ReactFieldError } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

interface IUpdatePhone {
  modalVisible: boolean
  setModalVisible: Dispatch<SetStateAction<boolean>>
}

export default function UpdatePhone(props: IUpdatePhone) {
  const formApi = useRef<FormApi>()
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  const [codeText, setCodeText] = useState('获取验证码')

  const timer = useRef<NodeJS.Timer>()

  const appDispatch = useAppDispatch()

  // 更新 userBaseInfo
  function doSetUserBaseInfo(userBaseInfo: IUserBaseInfoVO) {
    appDispatch(setUserBaseInfo(userBaseInfo))
  }

  useEffect(() => {
    return () => {
      clearTimer()
    }
  }, [timer])

  function clearTimer() {
    if (timer.current) {
      clearInterval(timer.current)
    }
  }

  return (
    <Modal
      title="修改手机"
      visible={props.modalVisible}
      onOk={() => {
        formApi.current?.submitForm()
      }}
      onCancel={() => {
        onModalCancel(props.setModalVisible, formApi.current, {})
      }}
      maskClosable={false}
      confirmLoading={confirmLoading}
    >
      <Form
        onSubmit={(form) => {
          if (confirmLoading) return
          modalSubmitClick(
            form as IUserCenterUpdatePhoneForm,
            setConfirmLoading,
            rsaPublicKey,
            props.setModalVisible,
            doSetUserBaseInfo
          )
        }}
        getFormApi={(api) => (formApi.current = api)}
        disabled={confirmLoading}
        onSubmitFail={(errors: Record<string, ReactFieldError>) => {
          errors.code ? ToastError(errors.code as string) : null
        }}
      >
        <Form.Input
          label={{ text: '验证账号密码', required: true }}
          field="password"
          validate={Validator['passwordValidate']}
          showClear
          mode="password"
        />
        <Form.Input
          field="phone"
          label={{ text: '手机号', required: true }}
          validate={Validator['phoneValidate']}
          showClear
        />
        <CEmailOrPhoneCode
          setCodeText={setCodeText}
          timer={timer}
          clearTimer={clearTimer}
          codeText={codeText}
          loading={confirmLoading}
          sendCodeType={6}
        ></CEmailOrPhoneCode>
      </Form>
    </Modal>
  )
}

// 表单提交
function modalSubmitClick(
  form: IUserCenterUpdatePhoneForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string,
  setModalVisible: Dispatch<SetStateAction<boolean>>,
  doSetUserBaseInfo: (userBaseInfo: IUserBaseInfoVO) => void
) {
  setConfirmLoading(true)

  form.password = passwordRSAEncrypt(form.password, rsaPublicKey)

  userCenterUpdatePhoneApi(form)
    .then(({ data }) => {
      ToastSuccess(data.msg)
      setConfirmLoading(false)
      setModalVisible(false)
      // 获取用户基本信息
      userCenterBaseInfoApi().then(({ data }) => {
        doSetUserBaseInfo(data.data)
      })
    })
    .catch(() => {
      setConfirmLoading(false)
    })
}
